import { loginByName } from '../services/user';
import { message } from 'antd';
import { stringify } from 'querystring';
import { history } from 'umi';

const TokenMangeModel = {
  namespace: 'login',
  state: {},
  effects: {
    *loginByName({ payload }, { call, put }) {
      const res = yield call(loginByName, payload);
      if (res) {
        console.log('res', res);
        if (res.success) {
          message.info('登录成功');
          localStorage.setItem('token', res.msg);
        } else {
          message.error(res.msg);
        }
      } else {
        message.error('登录请求失败');
      }
      return res;
    },

    logout() {
      localStorage.removeItem('token');
      localStorage.removeItem('roles');
      // 不是login界面的话跳转到login界面
      debugger;
      if (window.location.pathname !== '/user/login') {
        history.replace({
          pathname: '/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
    },
  },
  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
export default TokenMangeModel;
